#!/usr/bin/env python

from builtins import object

import sys, os, pickle

class PyHPBaseSession ( object ):
	def load ( self, sess_id ):
		pass

	def save ( self, sess_id ): #, data ):
		pass

	def delete ( self, sess_id ):
		pass

	def cleanup ( self ):
		pass

	def get ( self, name, defval = None ):
		pass

	def set ( self, name, val ):
		pass

class Session ( object ):
	def __init__ ( self, pyhp, sess_handler = None ):
		self._pyhp = pyhp
		#self.data = {}

		if not sess_handler:
			sess_handler = PyHPBaseSession ()

		self.id = None
		self.handler = sess_handler

		self._is_loaded = False

	def init ( self ):
		self._read_id ()

	def _read_id ( self ):
		cook = None

		# Cerco di leggere il session_id da __PYHP_SESSION
		num = self._pyhp.post.get ( "__PYHP_SESSION", self._pyhp.get.get ( "__PYHP_SESSION" ) )

		# Se non trovo num, cerco di leggerlo dal cookie "session"
		if not num:
			# Cerco di leggere il session_id dal cookie
			cook = self._pyhp.cookies.get ( "session" )
			if cook:
				num = cook.value

		self.id = num

	def start ( self, sess_handler = None , timeout = 60, domain = '' ):
		if sess_handler:
			self.handler = sess_handler
			self.handler._timeout = timeout

		self._resolve_id ()

		#self.load ()

		# Setto la sessione nel cookie
		self._pyhp.cookies.create ( "session", self.id )
		if timeout: self._pyhp.cookies.set ( "session", "expires", timeout * 60 )
		if domain: self._pyhp.cookies.set ( "session", "domain", domain )

		#sys.stderr.write ( "\n\n\n***** ID: %s\n\n\n" % self.id )

	def _resolve_id ( self ):
		if self.id: return

		self._read_id ()

		if not self.id:
			# Se arrivo fino a qui, significa che devo generare un nuovo valore di cookie
			import random, time
			try:
				import hashlib
				md5 = hashlib.md5 ()
			except:
				import md5
				md5 = md5.md5 ()

			random.seed ( time.time () )

			tmp = "%s-%s" % ( time.time (), random.uniform ( 0, 9000 ) )
			md5.update ( tmp )
			self.id = md5.hexdigest ()

	def save ( self ):
		if not self._is_loaded: return
		if not self.id: return
		self.handler.save ( self.id ) #, self.data )

	def load ( self ):
		if self._is_loaded: return

		self._resolve_id ()

		self.handler.load ( self.id )
		#self.data = self.handler.load ( self.id )
		#if not self.data: self.data = {}

		self._is_loaded = True

	def delete ( self ):
		if not self.id: return
		self.handler.delete ( self.id )
		#self.data = {}

	def cleanup ( self ):
		self.handler.cleanup ()
		self._is_loaded = False

	def set ( self, name, val ):
		self.load ()
		self.handler.set ( name, val )

	def get ( self, name, defval = None ):
		self.load ()
		return self.handler.get ( name, defval )
